﻿using System;
using System.Collections.Generic;
using System.Text;
using Bll;
using Common.CipherTextHelper;
using DtoModels;
using Entities;
using Microsoft.AspNetCore.Mvc;
using Portal.Models;
using SqlSugar;

namespace Portal.Controllers
{

    /// <summary>
    /// 用户管理
    /// </summary>
    public class UserController : Controller
    {
        private readonly SysUserBll _sysUserBll;
        private readonly SqlSugarClient _sqlSugarClient;

        public UserController(SysUserBll sysUserBll, SqlSugarClient sqlSugarClient)
        {
            _sysUserBll = sysUserBll;
            _sqlSugarClient = sqlSugarClient;
        }

        /// <summary>
        /// 查询所有用户
        /// </summary>
        /// <returns></returns>
        public ActionResult LoadAllUser(UserInfoReqDto userInfoReq)
        {
            var totalCount = 0;
            var queryResult = this._sysUserBll.LoadAllUser(userInfoReq, ref totalCount);

            return Json(new LayUiStandardResDto<LoadAllUserResDto>
            {
                Code = ResultCodeConst.OK,
                Msg = "查询成功",
                Count = totalCount,
                Data = queryResult
            });
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <returns></returns>
        public IActionResult AddUser(sys_user entity)
        {
            var insertNum = this._sqlSugarClient.Insertable(entity).ExecuteCommand();

            var result = new LayUiStandardResDto
            {
                Code = GlobalVariable.Ok,
                Msg = $"成功添加{insertNum}个用户"
            };

            return Json(result);
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult DeleteUser(int id)
        {
            var deleteNum = this._sqlSugarClient.Deleteable<sys_user>().Where(x => x.id == id).ExecuteCommand();
            var result = new LayUiStandardResDto
            {
                Code = GlobalVariable.Ok,
                Msg = $"成功删除 {deleteNum} 个用户"
            };

            return Json(result);
        }

        /// <summary>
        /// 重置用户密码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult ResetPwd(int id)
        {
            var curUser = this._sqlSugarClient.Queryable<sys_user>().Where(x => x.id == id).First();
            if (curUser == null)
            {
                var errorResult = new LayUiStandardResDto
                {
                    Code = GlobalVariable.Error,
                    Msg = "需要重置密码的用户不存在."
                };

                return Json(errorResult);
            }

            //此处目前按照初始密码123456来进行重置,后期我们可以随机生成一个初始密码设置到系统中,并通过短信,或者邮件的方式发送给用户.

            var initPwd = "123456";

            var md5Pwd = CipherTextHelper.GetMd5(initPwd, Encoding.UTF8);
            curUser.pwd = md5Pwd;

            var updateNum = this._sqlSugarClient.Updateable<sys_user>(curUser).ExecuteCommand();


            if (updateNum < 1)
            {
                var errorResult = new LayUiStandardResDto<object>
                {
                    Code = GlobalVariable.Error,
                    Msg = $"用户 { curUser.name } 登录密码初始化失败,请稍后再试."
                };

                return Json(errorResult);
            }

            var result = new LayUiStandardResDto<object>
            {
                Code = GlobalVariable.Ok,
                Msg = $"用户 {curUser.name} 登录密码已初始为 {initPwd}"
            };

            return Json(result);
        }

        /// <summary>
        /// 处理用户密码修改
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ProcessChangePwd(ProcessChangePwdResDto res)
        {

            var queryUser = this._sqlSugarClient.Queryable<sys_user>()
                .Where(x => x.loginname == res.loginName).ToList();

            if (queryUser.Count == 0)
            {
                return Json(new LayUiStandardResDto<object>
                {
                    Code = GlobalVariable.Error,
                    Msg = "用户不存在"
                });
            }

            var oldMd5Pwd = CipherTextHelper.GetMd5(res.oldPwd, Encoding.UTF8);

            var curUser = queryUser.Find(x => x.pwd == oldMd5Pwd);

            if (curUser == null)
            {
                return Json(new LayUiStandardResDto<object>
                {
                    Code = GlobalVariable.Error,
                    Msg = "旧密码不正确"
                });
            }

            curUser.pwd = CipherTextHelper.GetMd5(res.newPwd, Encoding.UTF8);

            var updateNum = this._sqlSugarClient.Updateable(curUser).ExecuteCommand();


            HttpContext.Session.Clear();
            return Json(new LayUiStandardResDto<object>
            {
                Code = GlobalVariable.Ok,
                Msg = "密码修改成功"
            });


        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="updateEntity"></param>
        /// <returns></returns>
        public IActionResult UpdateUser(sys_user updateEntity)
        {
            var updateNum = this._sqlSugarClient.Updateable<sys_user>(updateEntity).ExecuteCommand();
            if (updateNum < 1)
            {
                var errorResult = new LayUiStandardResDto<object>
                {
                    Code = GlobalVariable.Error,
                    Msg = $"用户 {updateEntity.name} 个人信息更新失败,请稍后再试."
                };

                return Json(errorResult);
            }

            var successResult = new LayUiStandardResDto<object>
            {
                Code = GlobalVariable.Ok,
                Msg = $"用户 {updateEntity.name} 个人信息更新成功."
            };

            return Json(successResult);
        }

        /// <summary>
        /// 根据用户Id获取用户角色
        /// </summary>
        /// <returns></returns>
        public IActionResult InitRoleByUserId(int id, int page, int limit)
        {


            //已经拥有的角色
            var existSql = $@"
select 

sr.id,        -- 角色id
sr.`name`,    -- 角色名称
sr.remark     -- 角色备注

from sys_user as su
left join sys_role_user as sru on su.id = sru.uid
left join sys_role as sr on sru.rid = sr.id

where 1 = 1
and su.id = {id}
";

            var existRoleResult = this._sqlSugarClient.Ado.SqlQuery<RoleByUserId>(existSql);


            if (existRoleResult.Count == 1 && existRoleResult[0].Id == 0)  //未分配任何角色
            {
                var notDistributionRoleSql = $@"
select 

sr.id,        -- 角色id
sr.`name`,    -- 角色名称
sr.remark     -- 角色备注

from sys_role as sr
";

                var notDistributionRoleResult = this._sqlSugarClient.Ado.SqlQuery<RoleByUserId>(notDistributionRoleSql);
                return Json(new
                {
                    Code = 0,
                    Msg = "查询成功",
                    Count = notDistributionRoleResult.Count,
                    Data = notDistributionRoleResult
                });

            }

            foreach (var item in existRoleResult)
            {
                item.IsChecked = true;
            }


            //还未拥有的角色
            var notExistSql = $@"
select 

sr.id,        -- 角色id
sr.`name`,    -- 角色名称
sr.remark     -- 角色备注

from sys_role as sr where sr.id not in (
select 
sru.rid 
from sys_user as su
left join sys_role_user as sru on su.id = sru.uid
where 1 = 1
and su.id = {id})

";

            var notExistRoleResult = this._sqlSugarClient.Ado.SqlQuery<RoleByUserId>(notExistSql);

            existRoleResult.AddRange(notExistRoleResult);

            return Json(new
            {
                Code = 0,
                Msg = "查询成功",
                Count = existRoleResult.Count,
                Data = existRoleResult
            });


        }


        /// <summary>
        /// 保存用户角色
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="ids"></param>
        /// <returns></returns>
        public IActionResult SaveUserRole(int uid, int[] ids)
        {
            var insertData = new List<sys_role_user>();
            foreach (var item in ids)
            {
                insertData.Add(new sys_role_user
                {
                    uid = uid,
                    rid = item
                });
            }


            //TODO:此处应该开启事务,保证业务数据一致性

            //删除之前已经存在的用户角色
            this._sqlSugarClient.Deleteable<sys_role_user>().Where(x => x.uid == uid).ExecuteCommand();
            this._sqlSugarClient.Insertable<sys_role_user>(insertData).ExecuteCommand();

            var successResult = new LayUiStandardResDto<object>
            {
                Code = GlobalVariable.Ok,
                Msg = $"角色分配成功."
            };

            return Json(successResult);
        }

        /// <summary>
        /// 指定用户Id的角色
        /// </summary>
        public class RoleByUserId
        {
            public int Id { get; set; }

            public string Name { get; set; }

            public string Remark { get; set; }

            public bool IsChecked { get; set; }
        }

        /// <summary>
        /// 用户地图
        /// </summary>
        /// <returns></returns>
        public IActionResult ChinaMap()
        {
            return View();
        }
    }
}